import axios from 'axios';
import Vue from "vue";
import store from "@/store";

let loadingState = null;

const service = axios.create({
    baseURL : process.env.VUE_APP_API_SERVER,
    timeout:20000
})

service.crossDomain = true;

service.interceptors.request.use(config=>{

    loadingState = Vue.prototype.$loading({
        lock: true,
        text: '数据加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
    })

    let token = store.state.token;
    if (token) {
        config.params =  config.params  || {}
        config.params.sid = token;
    }

    // if (config.method === 'post' && !config.headers['Content-Type']) {
    //     config.headers['Content-Type'] = 'application/json'
    // }
    console.log(config);

    return config;
})
service.interceptors.response.use(response=>{
    console.log(response)

    loadingState.close();

    if (response.status !== 200) {
        Vue.prototype.$alert('网络繁忙，请稍后再试！')
        return Promise.reject(response)
    }

    if (response.data.code !== 1) {

        Vue.prototype.$alert(response.data.msg)

        if(response.data.code === 2){
            store.dispatch('resetToken')
        }
        return Promise.reject(response.data);
    }

    // if (response.data.msg !== '') {
    //     Vue.prototype.$message.success(response.data.msg);
    //
    // }
    return response.data;

},(err)=>{
    loadingState.close();
    Vue.prototype.$alert(err);
    return Promise.reject(err);
})


export default service